import React from 'react';
import PropTypes from 'prop-types';
import { Dialog, Form, Input, Field, Checkbox, Balloon, Radio, Button } from '@teamix/ui';
import { ButtonIcon } from '@alife/devops-ui';
import docs from 'utils/docs';
import { getFeature } from 'utils/features';
import HistoryModal from '../historyModal';
import intl from '../../../../../../../../../../locale';

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    span: 6,
  },

  wrapperCol: {
    span: 20,
  },
};

export default class CreatePushRuleModal extends React.Component {
  static propTypes = {
    trigger: PropTypes.element,
    closeModal: PropTypes.func,
    create: PropTypes.func,
  };

  static defaultProps = {
    trigger: null,
    closeModal: () => { },
    create: () => { },
  };

  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.state = {
      submitting: false,
      isHistoryModalOpen: false,
      testUrl: '',
      // matchedBranchList: [],
    };
  }

  componentDidMount() {
    if (this.props.dialogType === 'create') return;
    let commitmsgRule;
    let emailRule;
    this.props.getPushRuleById(this.props.recordId, (result) => {
      const commit_check_rules = [];
      let is_commit_check_enable = false;
      let commit_check_level = '';
      let is_force_push_disable = false;
      result.rule_infos.forEach((rule) => {
        if (rule.checker_name === 'CommitMessageChecker') {
          commitmsgRule = rule.extra_message;
        }
        if (rule.checker_name === 'CommitAuthorEmailChecker') {
          emailRule = rule.extra_message;
        }
        if (['CommitAuthorChecker', 'CommitCommitterChecker'].includes(rule.checker_name)) {
          if (rule.extra_message) {
            is_commit_check_enable = true;
            commit_check_level = rule.checker_type;
            commit_check_rules.push(rule.checker_name);
          }
        }

        if (rule.checker_name === 'ForcePushChecker') {
          is_force_push_disable = !!rule.extra_message;
        }
      });
      this.field.setValues({
        ref_name: result.ref_name,
        commit_message_checker: commitmsgRule,
        commit_email_checker: emailRule,
        commit_check_rules,
        is_commit_check_enable,
        commit_check_level,
        is_force_push_disable,
      });
    });
  }

  onClose = () => {
    this.setState({
      submitting: false,
      testUrl: '',
      isHistoryModalOpen: false,
    });
    this.props.closeDialog();
    this.props.closeModal();
  };

  checkValidator = (rule, value, callback) => {
    if (value && value.length > 0) {
      callback();
    } else {
      callback(
        intl.get({
          id: 'code-assets.containers.createPushRule.SelectAtLeastOne',
          defaultMessage: '该项至少选中一个',
        }),
      );
    }
  };

  getThirdPartyCheck = () => {
    const formData = this.field.getValues();
    const { is_prehook_enable, prehook_checker_type, third_party_url } = formData;
    let rule = null;
    if (is_prehook_enable) {
      rule = {
        checker_name: 'ThirdPartyChecker',
        extra_message: '',
        checker_type: prehook_checker_type,
        third_party_url,
        third_party_timeout: '1000',
      };
    }
    return rule;
  };

  testPrehook = () => {
    const testUrl = this.field.getValue('third_party_url');
    if (!testUrl) {
      return;
    }
    this.setState({ isHistoryModalOpen: true, testUrl });
  };

  handleOk = () => {
    if (this.state.submitting) return;
    this.field.validate((errors) => {
      if (!errors) {
        this.setState({ submitting: true });
        const formData = this.field.getValues();
        const {
          commit_check_rules,
          is_commit_check_enable,
          commit_check_level,
          is_force_push_disable,
          org_push_rule,
        } = formData;

        const record = {
          ref_type: 'Branch',
          org_push_rule,
          ref_name: formData.ref_name,
          rule_infos: [
            {
              checker_name: 'CommitMessageChecker',
              extra_message: formData.commit_message_checker || '',
            },

            {
              checker_name: 'CommitAuthorEmailChecker',
              extra_message: formData.commit_email_checker || '',
            },

            {
              checker_name: 'CommitAuthorChecker',
              extra_message:
                is_commit_check_enable && commit_check_rules.includes('CommitAuthorChecker')
                  ? 'on'
                  : '',
              checker_type: commit_check_level,
            },
            {
              checker_name: 'CommitCommitterChecker',
              extra_message:
                is_commit_check_enable && commit_check_rules.includes('CommitCommitterChecker')
                  ? 'on'
                  : '',
              checker_type: commit_check_level,
            },
            {
              checker_name: 'ForcePushChecker',
              extra_message: is_force_push_disable ? 'disabled' : '',
            },
          ],
        };

        const thirdPartyRule = this.getThirdPartyCheck();
        if (thirdPartyRule) {
          record.rule_infos.push(thirdPartyRule);
        }

        if (this.props.dialogType === 'create') {
          this.props.create(record, this.callback);
        } else {
          this.props.edit(this.props.recordId, record, this.callback);
        }
      }
    });
  };

  callback = (isFail) => {
    if (!isFail) {
      this.field.reset();
    }
    this.setState({ submitting: false });
    this.onClose();
  };

  render() {
    const { init } = this.field;
    const { isHistoryModalOpen, testUrl } = this.state;
    // const { matchedBranchList } = this.state;
    // const { record = {} } = this.props;
    // const {
    //   ref_name = '',
    // } = record;

    return (
      <React.Fragment>
        <Dialog
          title={
            <div>
              {this.props.dialogType === 'create' ?
                intl.get({
                  id: 'code-assets.containers.createPushRule.CreateAPushRule',
                  defaultMessage: '新建推送规则',
                })
                :
                '编辑推送规则'
              }
            </div>
          }
          visible
          style={{ width: '600px' }}
          onOk={this.handleOk}
          onCancel={this.onClose}
          onClose={this.onClose}
          footerActions={['cancel', 'ok']}
          okProps={{ loading: this.state.submitting }}
        >
          <Form {...formItemLayout} field={this.field} labelAlign="top">
            <FormItem
              label={intl.get({
                id: 'code-assets.containers.createPushRule.Branch',
                defaultMessage: '分支',
              })}
              required
              help={<div className="branch-name-tip">仅支持选择全部分支</div>}
            >
              <Input {...init('ref_name', { initValue: '**' })} disabled />
            </FormItem>
            <FormItem
              label={intl.get({
                id: 'code-assets.containers.createPushRule.SubmitComments',
                defaultMessage: '提交注释',
              })}
              help={
                <div className="branch-name-tip">
                  {intl.get({
                    id: 'code-assets.containers.createPushRule.CommentsSubmittedMustConformTo',
                    defaultMessage:
                      '提交注释需符合正则表达式才允许推送，为空表示允许所有提交注释',
                  })}
                </div>
              }
            >
              <Input
                autoFocus
                placeholder={intl.get({
                  id: 'code-assets.containers.createPushRule.ForExampleFixAZ',
                  defaultMessage: '如：^fix #[A-Z]+\\-[0-9]+',
                })}
                maxLength={500}
                hasLimitHint
                {...init('commit_message_checker')}
              />
            </FormItem>
            <FormItem
              label={intl.get({
                id: 'code-assets.containers.createPushRule.SubmitEmail',
                defaultMessage: '提交邮箱',
              })}
              help={
                <div className="branch-name-tip">
                  {intl.get({
                    id: 'code-assets.containers.createPushRule.TheSenderSCommitterMailbox',
                    defaultMessage:
                      '提交人（Committer）邮箱需符合正则表达式匹配才允许推送，为空表示允许所有邮箱',
                  })}
                </div>
              }
            >
              <Input
                maxLength={500}
                hasLimitHint
                placeholder={intl.get({
                  id: 'code-assets.containers.createPushRule.ForExampleCodeupCom',
                  defaultMessage: '如：@codeup\\.com$',
                })}
                {...init('commit_email_checker')}
              />
            </FormItem>

            <Form.Item {...init('is_force_push_disable')} label="" style={{ marginBottom: 0 }}>
              <Checkbox checked={this.field.getValue('is_force_push_disable')}>
                <span style={{ position: 'relative' }}>
                  {intl.get({
                    id: 'code-assets.containers.createPushRule.ForcePushProhibitedForcePush',
                    defaultMessage: '禁止强制推送（Force Push）',
                  })}

                  <Balloon.Tooltip
                    trigger={
                      <ButtonIcon
                        name="question-line"
                        style={{ position: 'absolute', top: '-2px', marginLeft: '-4px' }}
                      />
                    }
                    popupStyle={{
                      maxWidth: 'none',
                      width: 340,
                    }}
                    align="t"
                  >
                    {intl.get({
                      id: 'code-assets.containers.createPushRule.AfterThisFeatureIsEnabled',
                      defaultMessage: '开启后将不允许使用 git push -f 强制修改提交历史',
                    })}
                  </Balloon.Tooltip>
                </span>
              </Checkbox>
            </Form.Item>

            <Form.Item
              {...init('is_commit_check_enable', {
                props: {
                  onChange: (value) => {
                    if (value) {
                      this.field.setValue('commit_check_level', 'warn');
                      this.field.setValue('commit_check_rules', ['CommitAuthorChecker']);
                    } else {
                      this.field.setValue('commit_check_level', '');
                      this.field.setValue('commit_check_rules', []);
                    }
                  },
                },
              })}
              label=""
              style={{ marginBottom: 0 }}
            >
              <Checkbox checked={this.field.getValue('is_commit_check_enable')}>
                <span style={{ position: 'relative' }}>
                  {intl.get({
                    id: 'code-assets.containers.createPushRule.TheCodeBelongsToThe',
                    defaultMessage: '代码属主检查',
                  })}

                  <Balloon
                    closable={false}
                    trigger={
                      <ButtonIcon
                        name="question-line"
                        style={{ marginLeft: 4, position: 'absolute', top: '-2px' }}
                      />
                    }
                    align="t"
                  >
                    {intl.get({
                      id: 'code-assets.containers.createPushRule.CheckWhetherTheEmailInformation',
                      defaultMessage: '检查代码作者或者提交者邮箱信息是否与当前用户主邮箱一致。',
                    })}
                    <a target="_blank" href={docs('commit-check-repo')} rel="noreferrer">
                      {intl.get({
                        id: 'code-assets.containers.createPushRule.HowToUse',
                        defaultMessage: '如何使用',
                      })}
                    </a>{' '}
                    ？
                  </Balloon>
                </span>
              </Checkbox>
            </Form.Item>
            {this.field.getValue('is_commit_check_enable') && (
              <React.Fragment>
                <Form.Item
                  className="push-rule-check-rules"
                  label={''}
                  labelAlign="left"
                  style={{ marginBottom: 0 }}
                >
                  <span>
                    {intl.get({
                      id: 'code-assets.containers.createPushRule.CheckRules',
                      defaultMessage: '检查规则：',
                    })}
                  </span>
                  <Checkbox.Group
                    style={{ display: 'inline-block', width: 410 }}
                    {...init('commit_check_rules', {
                      initValue: [],
                      rules: [
                        {
                          validator: this.checkValidator,
                        },
                      ],
                    })}
                  >
                    <Checkbox value={'CommitAuthorChecker'}>
                      {intl.get({
                        id: 'code-assets.containers.createPushRule.CheckAuthorAuthor',
                        defaultMessage: '检查作者（Author）',
                      })}
                    </Checkbox>
                    <Checkbox value={'CommitCommitterChecker'}>
                      {intl.get({
                        id: 'code-assets.containers.createPushRule.CheckSubmitterCommitter',
                        defaultMessage: '检查提交者（Committer）',
                      })}
                    </Checkbox>
                  </Checkbox.Group>
                </Form.Item>
                <Form.Item label={''} labelAlign="left">
                  <span>
                    {intl.get({
                      id: 'code-assets.containers.createPushRule.Limits',
                      defaultMessage: '限制级别：',
                    })}
                  </span>
                  <Radio.Group
                    className="settings-repos-checkgroup"
                    {...init('commit_check_level')}
                  >
                    <Radio value={'block'}>
                      {intl.get({
                        id: 'code-assets.containers.createPushRule.NoPush',
                        defaultMessage: '禁止推送',
                      })}
                    </Radio>
                    <Radio value={'warn'}>
                      {intl.get({
                        id: 'code-assets.containers.createPushRule.WarningOnlyPushAllowed',
                        defaultMessage: '仅警告，允许推送',
                      })}
                    </Radio>
                  </Radio.Group>
                </Form.Item>
              </React.Fragment>
            )}
            {/* 三方系统验证 */}
            {
              getFeature('project.setting.push_rules.third_party') ?
                <>
                  <Form.Item
                    label=""
                    labelTextAlign="left"
                    {...init('is_prehook_enable', {
                      props: {
                        onChange: (value) => {
                          if (value) {
                            this.field.setValue('prehook_checker_type', 'warn');
                            this.field.setValue('third_party_url', '');
                          } else {
                            this.field.setValue('prehook_checker_type', '');
                            this.field.setValue('third_party_url', '');
                          }
                        },
                      },
                    })}
                  >
                    <Checkbox checked={this.field.getValue('is_prehook_enable')}>
                      <span style={{ position: 'relative' }}>
                        三方系统验证
                        <Balloon
                          closable={false}
                          trigger={
                            <ButtonIcon
                              name="question-line"
                              style={{ marginLeft: 4, position: 'absolute', top: '-2px' }}
                            />
                          }
                          align="t"
                        >
                          <a target="_blank" href={docs('third-confirm')} rel="noreferrer">如何使用三方系统验证？</a>
                        </Balloon>
                      </span>
                    </Checkbox>
                  </Form.Item>
                  {this.field.getValue('is_prehook_enable') && (
                    <React.Fragment>
                      <Form.Item label={''} labelAlign="left">
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                          <span style={{ marginRight: 24 }}>URL 地址：</span>
                          <Input
                            placeholder="请输入三方系统地址"
                            className="prehook-url"
                            {...this.field.init('third_party_url', {
                              initValue: '',
                              rules: [
                                {
                                  required: true,
                                  message: '该项为必填项',
                                },

                                {
                                  validator: this.URLValidator,
                                },
                              ],
                            })}
                          />

                          <Button
                            type="primary"
                            className="test-prehook-btn"
                            onClick={this.testPrehook}
                            style={{ marginLeft: 24 }}
                          >
                            测试链接
                          </Button>
                        </div>
                      </Form.Item>
                      <Form.Item label={''} labelAlign="left">
                        <span style={{ position: 'relative', top: '2px' }}>
                          异常处理
                          <Balloon.Tooltip
                            type="normal"
                            trigger={
                              <ButtonIcon
                                name="information-line"
                                style={{ position: 'relative', top: '-2px' }}
                              />
                            }
                            align="t"
                          >
                            设置三方系统返回异常的处理，其中超时时间默认 1 秒
                          </Balloon.Tooltip>
                          ：
                        </span>
                        <Radio.Group
                          className="settings-repos-checkgroup"
                          {...this.field.init('prehook_checker_type', {})}
                        >
                          <Radio value={'block'}>验证不通过</Radio>
                          <Radio value={'warn'}>忽略规则，验证通过</Radio>
                        </Radio.Group>
                      </Form.Item>
                    </React.Fragment>
                  )}
                </>
                :
                null
            }
          </Form>
        </Dialog>
        {isHistoryModalOpen && (
          <HistoryModal
            isModalOpen={isHistoryModalOpen}
            testUrl={testUrl}
            closeModal={() => {
              this.setState({
                isHistoryModalOpen: false,
                testUrl: '',
              });
            }}
          />
        )}
      </React.Fragment>
    );
  }
}
